<script setup lang="ts">
import {onMounted, ref} from 'vue'
import {Avatar, Card, Tag, Button, Divider, Row, Col, Descriptions, message, Modal, Input} from 'ant-design-vue'
import {ArrowLeftOutlined, MessageOutlined, UserAddOutlined, StarOutlined} from '@ant-design/icons-vue'
import {useRoute, useRouter} from 'vue-router'
import {getTeamById, joinTeam} from "@/api/teamController.ts";
import {useLoginUserStore} from "@/stores/useLoginUserStore.ts";

const router = useRouter()
const route = useRoute()
const teamId = route.params.id
const loginUserStore = useLoginUserStore()

// 密码输入模态框相关状态
const passwordModalVisible = ref(false)
const password = ref('')

// 返回上一页
const goBack = () => {
  router.back()
}

// 模拟队伍数据，根据用户提供的格式
const teamDetail = ref({
  id: "6",
  teamname: "大碗宽面",
  description: "这碗大，别让那虚荣心作祟；真心话，这大碗宽面也很贵",
  avatar: "https://homie-match-1361877603.cos.ap-beijing.myqcloud.com/picture/team/avatar/6/2025-09-16_V3BfJgvnEZSezXve.png",
  tags: [],
  maxPerson: 7,
  userVO: {
    id: "1",
    userAccount: "admin",
    username: "管理员",
    userAvatar: "https://cloud-picture-1361877603.cos.ap-guangzhou.myqcloud.com/public/1/2025-09-11_ze1A7F3vUcHALYrf.webp",
    userProfile: "大家嚎",
    userTags: ["qwq"],
    teach: ["音乐", "美术"],
    learn: ["六级", "雅思"],
    userRole: "admin",
    status: 1,
    points: 123,
    blogCount: 0,
    blogTotalView: "0",
    likeCount: 0,
    collectCount: 0,
    followCount: 1,
    fanCount: 0,
    createTime: "2025-09-14T05:06:39.000+00:00",
    updateTime: "2025-09-24T07:54:33.000+00:00"
  },
  memberVOs: [
    {
      id: "7",
      userAccount: "user7",
      username: "无名7",
      userAvatar: null,
      userProfile: null,
      userTags: ["qwq", "qaq"],
      teach: ["java", "python"],
      learn: ["六级", "雅思"],
      userRole: "user",
      status: 1,
      points: 0,
      blogCount: 0,
      blogTotalView: "0",
      likeCount: 0,
      collectCount: 0,
      followCount: 0,
      fanCount: 0,
      createTime: "2025-09-14T06:40:31.000+00:00",
      updateTime: "2025-09-15T09:31:13.000+00:00"
    },
    {
      id: "8",
      userAccount: "user8",
      username: "无名8",
      userAvatar: null,
      userProfile: null,
      userTags: ["qwq", "qaq"],
      teach: ["java", "python"],
      learn: ["六级", "雅思"],
      userRole: "user",
      status: 1,
      points: 0,
      blogCount: 0,
      blogTotalView: "0",
      likeCount: 0,
      collectCount: 0,
      followCount: 0,
      fanCount: 0,
      createTime: "2025-09-14T06:40:31.000+00:00",
      updateTime: "2025-09-15T09:31:14.000+00:00"
    },
    {
      id: "9",
      userAccount: "user9",
      username: "无名9",
      userAvatar: null,
      userProfile: null,
      userTags: ["qwq", "qaq"],
      teach: ["java", "python"],
      learn: ["六级", "雅思"],
      userRole: "user",
      status: 1,
      points: 0,
      blogCount: 0,
      blogTotalView: "0",
      likeCount: 0,
      collectCount: 0,
      followCount: 0,
      fanCount: 0,
      createTime: "2025-09-14T06:40:31.000+00:00",
      updateTime: "2025-09-15T09:31:15.000+00:00"
    },
    {
      id: "10",
      userAccount: "user10",
      username: "无10",
      userAvatar: null,
      userProfile: null,
      userTags: ["qwq", "qaq"],
      teach: ["java", "python"],
      learn: ["六级", "雅思"],
      userRole: "user",
      status: 1,
      points: 0,
      blogCount: 0,
      blogTotalView: "0",
      likeCount: 0,
      collectCount: 0,
      followCount: 0,
      fanCount: 0,
      createTime: "2025-09-14T06:40:31.000+00:00",
      updateTime: "2025-09-15T09:31:16.000+00:00"
    }
  ],
  status: 0,
  createTime: "2025-09-16T06:40:31.000+00:00"
})

// 获取队伍状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '公开'
    case 1:
      return '私有'
    case 2:
      return '加密'
    default:
      return '未知'
  }
}

// 获取队伍状态颜色
const getStatusColor = (status: number) => {
  switch (status) {
    case 0:
      return 'green'
    case 1:
      return 'orange'
    case 2:
      return 'blue'
    default:
      return 'default'
  }
}

const doJoinTeam = async () => {
  if (teamDetail.value.status === 1) {
    // 如果队伍是加密的，显示密码输入框
    password.value = '';
    passwordModalVisible.value = true;
  } else {
    const res = await joinTeam({
      teamId: route.params.id,
      userId: loginUserStore.loginUser.id,
      password: password.value
    })
    if (res.data.code === 0 && res.data.data) {
      message.success("加入成功")
      await fetchData()
    } else {
      message.error("加入失败，" + res.data.message)
    }
  }
}

// 确认加入队伍（带密码）
const handleConfirmJoin = async () => {
  passwordModalVisible.value = false;
  const res = await joinTeam({
    teamId: route.params.id,
    userId: loginUserStore.loginUser.id,
    password: password.value
  })
  if (res.data.code === 0 && res.data.data) {
    message.success("加入成功")
    await fetchData()
  } else {
    message.error("加入失败，" + res.data.message)
  }
}

// 取消加入
const handleCancelJoin = () => {
  passwordModalVisible.value = false;
  password.value = '';
}

// 跳转到用户详情页
const goToUserDetail = (userId: string) => {
  router.push(`/user/${userId}`)
}

// 联系队长
const contactTeamLeader = () => {
  const captainId = teamDetail.value.userVO.id;
  router.push(`/chat?id=${captainId}&type=user`)
}
const fetchData = async () => {
  const res = await getTeamById({
    id: route.params.id
  })
  if (res.data.code === 0 && res.data.data) {
    teamDetail.value = res.data.data
  } else {
    message.error("获取数据失败，" + res.data.message)
  }
}

onMounted(() => {
  console.log(route.params.id)
  fetchData()
})
</script>

<template>
  <div id="TeamDetailPage">
    <div class="team-detail-container">
      <!-- 返回按钮 -->
      <div class="back-button-container">
        <a-button type="text" @click="goBack">
          <template #icon>
            <ArrowLeftOutlined/>
          </template>
          返回
        </a-button>
      </div>

      <!-- 队伍头部信息 -->
      <div class="team-header">
        <Avatar :src="teamDetail.avatar" size="large"/>

        <div class="team-name-section">
          <div class="teamname-container">
            <h1 class="teamname">{{ teamDetail.teamname }}</h1>
            <Tag :color="getStatusColor(teamDetail.status)">{{ getStatusText(teamDetail.status) }}</Tag>
            <div class="team-actions">
              <a-button type="primary" @click="doJoinTeam" class="join-button">
                <template #icon>
                  <UserAddOutlined/>
                </template>
                加入队伍
              </a-button>

              <a-button type="default" class="message-button" @click="contactTeamLeader">
                <template #icon>
                  <MessageOutlined/>
                </template>
                联系队长
              </a-button>
            </div>
          </div>
          <div class="team-basic-info">
            <span>创建时间: 2025-09-16</span>
            <span>成员数: {{ teamDetail.memberVOs.length + 1 }}/{{ teamDetail.maxPerson }}</span>
          </div>
        </div>
      </div>

      <Divider/>

      <!-- 队伍简介 -->
      <div class="team-profile-section">
        <h2 class="section-title">队伍介绍</h2>
        <p class="team-profile">{{ teamDetail.description }}</p>
      </div>

      <!-- 队伍标签 -->
      <div v-if="teamDetail.tags && teamDetail.tags.length > 0" class="team-tags-section">
        <h2 class="section-title">队伍标签</h2>
        <div class="tags-container">
          <Tag v-for="tag in teamDetail.tags" :key="tag" class="team-tag">
            {{ tag }}
          </Tag>
        </div>
      </div>

      <Divider/>

      <!-- 队伍成员 -->
      <div class="team-members-section">
        <h2 class="section-title">队伍成员</h2>

        <!-- 队长 -->
        <div class="captain-section">
          <h3 class="sub-section-title">队长</h3>
          <div class="member-item captain-item" @click="goToUserDetail(teamDetail.userVO.id)">
            <Avatar :src="teamDetail.userVO.userAvatar"/>
            <div class="member-info">
              <div class="member-name-row">
                <span class="member-name">{{ teamDetail.userVO.username }}</span>
                <Tag color="red">队长</Tag>
              </div>
              <div class="member-skills">
                <span class="skill-label">擅长:</span>
                <Tag v-for="skill in teamDetail.userVO.teach" :key="skill" color="green" class="skill-tag">
                  {{ skill }}
                </Tag>
              </div>
            </div>
          </div>
        </div>

        <!-- 成员列表 -->
        <div class="members-list-section">
          <h3 class="sub-section-title">成员 ({{ teamDetail.memberVOs.length }})</h3>
          <div class="members-grid">
            <div v-for="member in teamDetail.memberVOs" :key="member.id" class="member-item"
                 @click="goToUserDetail(member.id)">
              <Avatar :src="member.userAvatar"/>
              <div class="member-info">
                <div class="member-name-row">
                  <span class="member-name">{{ member.username }}</span>
                </div>
                <div class="member-skills">
                  <span class="skill-label">擅长:</span>
                  <Tag v-for="skill in member.teach" :key="skill" color="green" class="skill-tag">
                    {{ skill }}
                  </Tag>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  
  <!-- 密码输入模态框 -->
  <a-modal
      v-model:visible="passwordModalVisible"
      title="加入加密队伍"
      @ok="handleConfirmJoin"
      @cancel="handleCancelJoin"
      okText="确认"
      cancelText="取消"
  >
    <div style="margin-bottom: 16px;">
      <p>该队伍需要密码才能加入，请输入密码：</p>
    </div>
    <a-input
        v-model:value="password"
        type="password"
        placeholder="请输入队伍密码"
        allow-clear
        style="width: 100%;"
    />
  </a-modal>
  </div>
</template>

<style scoped>
#TeamDetailPage {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 24px 0;
}

.team-detail-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 32px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.back-button-container {
  margin-bottom: 24px;
}

.team-header {
  display: flex;
  align-items: center;
  gap: 24px;
  margin-bottom: 32px;
}

.team-name-section {
  flex: 1;
}

.teamname-container {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.teamname-container .team-actions {
  margin-left: auto;
  display: flex;
  gap: 8px;
}

.teamname {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.team-basic-info {
  display: flex;
  gap: 24px;
  font-size: 14px;
  color: #666;
  flex-wrap: wrap;
}

.team-profile-section {
  margin-bottom: 32px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.sub-section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
}

.team-profile {
  font-size: 16px;
  line-height: 1.8;
  color: #666;
  margin: 0;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 4px;
}

.team-tags-section {
  margin-bottom: 32px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  min-height: 32px;
  align-items: center;
}

.team-tag {
  font-size: 14px;
  padding: 4px 12px;
}

.team-members-section {
  margin-top: 32px;
}

.captain-section {
  margin-bottom: 32px;
}

.members-list-section {
  margin-bottom: 24px;
}

.captain-item {
  padding: 16px;
  background-color: #f0f9ff;
  border-radius: 8px;
  border: 1px solid #bae7ff;
}

.member-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 8px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.member-item:hover {
  background-color: #f0f0f0;
}

.member-info {
  flex: 1;
}

.member-name-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.member-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.member-skills {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.skill-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.skill-tag {
  font-size: 12px;
  padding: 2px 8px;
}

.members-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.team-actions {
  display: flex;
  gap: 12px;
}

.join-button {
  min-width: 120px;
}

.message-button {
  min-width: 120px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .team-detail-container {
    padding: 20px;
  }

  .team-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .teamname-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .teamname-container .team-actions {
    margin-left: 0;
    width: 100%;
    justify-content: flex-start;
  }

  .team-basic-info {
    flex-direction: column;
    gap: 8px;
  }

  .members-grid {
    grid-template-columns: 1fr;
  }
}
</style>
